﻿#include "gamewin.h"
#include "ui_gamewin.h"
#include "gamesce.h"
#include "card.h"
#include "board.h"
#include "button.h"
#include "roundbutton.h"
#include "dialogask.h"
#include "playerinfo.h"
#include "gamemanager.h"
#include "dialogonline.h"
#include "gamemanageronline.h"

#include <QFile>
#include <QSequentialAnimationGroup>
#include <QPixmap>
#include <QBrush>
#include <QPainter>
#include <QGraphicsPixmapItem>
#include <algorithm>
#include <random>
#include <QtMath>
#include <QSignalTransition>
#include <QtCore/qstate.h>
#include <QStateMachine>
#include <QMessageBox>
#include <QAbstractButton>

#define WIN_WIDTH 1050
#define WIN_HEIGHT 850
#define CELL_WIDTH 136
#define CELL_HEIGHT 160
#define CELL_MARGIN 16

GameWin::GameWin(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GameWin)
{
    initControl();

    initMusic();

    initWelcome();

    initHelp();

    ui->setupUi(this);
}

GameWin::~GameWin()
{
    delete ui;
}

void GameWin::initControl()
{
    auto loadStyleSheet = [this](QString sheetName){
        QFile file(":/Monster_Kill/Res/Qss/" + sheetName + ".css");
        if(file.open(QFile::ReadOnly)){
            QString strStyleSheet = this->styleSheet();
            strStyleSheet += file.readAll();
            this->setStyleSheet(strStyleSheet);
            file.close();
        }
    };

    loadStyleSheet("GameWin_Welcome");

    QRectF tempRect(0, 0, WIN_WIDTH, WIN_HEIGHT);
    m_scene = new GameSce(this, tempRect);

    m_View = new QGraphicsView(m_scene, this);
    m_View->resize(m_scene->width(), m_scene->height());
    m_View->setScene(m_scene); // 设置游戏场景
    m_View->setStyleSheet("border:none; background:transparent;"); // 视图无边框透明设置
    m_View->setCacheMode(QGraphicsView::CacheBackground); // 设置缓存为背景模式
    m_View->show();

}

void GameWin::initMusic()
{
    m_welcomeBgm = new QMediaPlayer(this);
    m_gameBgm = new QMediaPlayer(this);

    m_welcomeList = new QMediaPlaylist(this);
    m_gameList = new QMediaPlaylist(this);

    m_welcomeList->addMedia(QUrl("qrc:/Monster_Kill/Res/Sound/Welcome.mp3"));
    m_welcomeList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    m_welcomeBgm->setPlaylist(m_welcomeList);
    m_welcomeBgm->setVolume(31);

    m_gameList->addMedia(QUrl("qrc:/Monster_Kill/Res/Sound/GameFight.mp3"));
    m_gameList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    m_gameBgm->setPlaylist(m_gameList);
    m_gameBgm->setVolume(43);

    m_welcomeBgm->play();

}

void GameWin::initWelcome()
{
    // 绘制游戏进场动画
    const int nLetters = 6;
    struct{
        char const* pix;
        qreal initX, initY;
        qreal destX, destY;
    }letterData[nLetters] = {
    {"4", 0, -2000, 175, 194}, // 第三行
    {"X", 0, -2000, 275, 194},
    {"4", 0, -2000, 375, 194},
    {"斗", 0, -2000, 475, 187},
    {"兽", 0, -2000, 600, 187},
    {"棋", 0, -2000, 725, 187}
    };

    QSequentialAnimationGroup* letterGroupMoving =
            new QSequentialAnimationGroup(this);

    for(int i = 0; i < nLetters; i++){
        // 文本图形项
        QString htmlText = QString("<span style=\"font-family:'方正舒体';font-size:138px;font-weight:817;color:#FFD770;\">%1</span>")
                .arg(letterData[i].pix);
        QGraphicsTextItem* letter = new QGraphicsTextItem();
        letter->setHtml(htmlText);
        letter->setPos(letterData[i].initX, letterData[i].initY);

        // 文本项属性动画
        QPropertyAnimation* moveAnimation =
                new QPropertyAnimation(letter, "pos", letterGroupMoving);
        // 设置字符动画结束的位置
        moveAnimation->setEndValue(QPointF(letterData[i].destX, letterData[i].destY));
        moveAnimation->setDuration(262);
        moveAnimation->setEasingCurve(QEasingCurve::OutElastic);
        letterGroupMoving->addPause(50);

        m_scene->addItem(letter); // 往游戏场景中添加字符图形项
    }
    letterGroupMoving->start(QAbstractAnimation::DeleteWhenStopped); // 动画停止后删除

    // 绘制按钮
    int tempX = WIN_WIDTH / 2;
    int tempY = WIN_HEIGHT / 9 * 5 - 37;
    m_buttonStart = new Button(m_scene, "开始游戏");
    m_buttonStart->setPos(tempX, tempY);
    connect(m_buttonStart, &Button::clicked, this, &GameWin::switchTOgame);

    m_buttonHelp = new Button(m_scene, "玩法说明");
    m_buttonHelp->setPos(tempX, tempY + 140);
    connect(m_buttonHelp, &Button::clicked, this, &GameWin::switchTOhelp);

    m_buttonExit = new Button(m_scene, "退出游戏");
    m_buttonExit->setPos(tempX, tempY + 280);
    connect(m_buttonExit, &Button::clicked, this, &GameWin::close);


}

void GameWin::initHelp()
{
    QRectF tempRect(0, 0, WIN_WIDTH, WIN_HEIGHT);
    m_sceneHelp = new GameSce(this, tempRect);

    // 绘制背景
    QPixmap tempPixmap(":/Monster_Kill/Res/Img/Back.png");
    QBrush tempBrush(tempPixmap);
    m_sceneHelp->setBackgroundBrush(tempBrush);

    // 绘制按钮
    int tempX = WIN_WIDTH / 2;
    int tempY = WIN_HEIGHT / 9 * 5;
    m_buttonBack_help = new Button(m_sceneHelp, "返回主页");
    m_buttonBack_help->setPos(tempX, tempY + 240);
    connect(m_buttonBack_help, &Button::clicked, this, &GameWin::switchTOwelcome);

    // 绘制标题
    QString strTitle("鼠标悬停后，按W、A、S、D进行移动");
    QString htmlText = QString("<span style=\"font-family:'宋体';font-size:55px;font-weight:734;color:#CC4800;\">%1</span>")
            .arg(strTitle);
    QGraphicsTextItem* title = new QGraphicsTextItem();
    title->setHtml(htmlText);
    title->setPos(tempX / 7, tempY - 227);
    m_sceneHelp->addItem(title);

    // 绘制说明图片
    // 大象
    QPixmap tempLoad;
    tempLoad.load(":/Monster_Kill/Res/Img/Animal/elephant.png");
    QPixmap pixmap_elephant = tempLoad.scaled(QSize(167, 167),
                                    Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QGraphicsPixmapItem* pixItem_elephant = new QGraphicsPixmapItem(pixmap_elephant);
    pixItem_elephant->setPos(tempX / 8, tempY - 130);

    // 老虎
    tempLoad.load(":/Monster_Kill/Res/Img/Animal/tiger.png");
    QPixmap pixmap_tiger = tempLoad.scaled(QSize(167, 167),
                                    Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QGraphicsPixmapItem* pixItem_tiger = new QGraphicsPixmapItem(pixmap_tiger);
    pixItem_tiger->setPos(tempX / 8 + 250, tempY - 130);

    // 狮子
    tempLoad.load(":/Monster_Kill/Res/Img/Animal/lion.png");
    QPixmap pixmap_lion = tempLoad.scaled(QSize(167, 167),
                                    Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QGraphicsPixmapItem* pixItem_lion = new QGraphicsPixmapItem(pixmap_lion);
    pixItem_lion->setPos(tempX / 8 + 500, tempY - 130);

    // 豹子
    tempLoad.load(":/Monster_Kill/Res/Img/Animal/cheetah.png");
    QPixmap pixmap_cheetah = tempLoad.scaled(QSize(167, 167),
                                    Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QGraphicsPixmapItem* pixItem_cheetah = new QGraphicsPixmapItem(pixmap_cheetah);
    pixItem_cheetah->setPos(tempX / 8 + 750, tempY - 130);

    // 狼
    tempLoad.load(":/Monster_Kill/Res/Img/Animal/wolf.png");
    QPixmap pixmap_wolf = tempLoad.scaled(QSize(167, 167),
                                    Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QGraphicsPixmapItem* pixItem_wolf = new QGraphicsPixmapItem(pixmap_wolf);
    pixItem_wolf->setPos(tempX / 8 + 750, tempY + 50);

    // 狗
    tempLoad.load(":Monster_Kill/Res/Img/Animal/dog.png");
    QPixmap pixmap_dog = tempLoad.scaled(QSize(167, 167),
                                    Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QGraphicsPixmapItem* pixItem_dog = new QGraphicsPixmapItem(pixmap_dog);
    pixItem_dog->setPos(tempX / 8 + 500, tempY + 50);

    // 猫
    tempLoad.load(":Monster_Kill/Res/Img/Animal/cat.png");
    QPixmap pixmap_cat = tempLoad.scaled(QSize(167, 167),
                                    Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QGraphicsPixmapItem* pixItem_cat = new QGraphicsPixmapItem(pixmap_cat);
    pixItem_cat->setPos(tempX / 8 + 250, tempY + 50);

    // 老鼠
    tempLoad.load(":Monster_Kill/Res/Img/Animal/rat.png");
    QPixmap pixmap_rat = tempLoad.scaled(QSize(167, 167),
                                    Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QGraphicsPixmapItem* pixItem_rat = new QGraphicsPixmapItem(pixmap_rat);
    pixItem_rat->setPos(tempX / 8, tempY + 50);

    // 图片汇总
    m_sceneHelp->addItem(pixItem_elephant);
    m_sceneHelp->addItem(pixItem_tiger);
    m_sceneHelp->addItem(pixItem_lion);
    m_sceneHelp->addItem(pixItem_cheetah);
    m_sceneHelp->addItem(pixItem_wolf);
    m_sceneHelp->addItem(pixItem_dog);
    m_sceneHelp->addItem(pixItem_cat);
    m_sceneHelp->addItem(pixItem_rat);

    // 绘制说明文字
    QPixmap pixmap_helpFont(":/Monster_Kill/Res/Img/HelpFont.png");
    QBrush brush_help(pixmap_helpFont);

    m_sceneHelp->setForegroundBrush(brush_help);

}

void GameWin::initGame()
{
    QRectF tempRect(0, 0, WIN_WIDTH, WIN_HEIGHT);
    m_sceneGame = new GameSce(this, tempRect);

    // 绘制背景
    QPixmap tempPixmap(":/Monster_Kill/Res/Img/Back4.png");
    QBrush tempBrush(tempPixmap);
    m_sceneGame->setBackgroundBrush(tempBrush);

    // 绘制按钮
    int tempX = WIN_WIDTH / 2;
    int tempY = WIN_HEIGHT / 9 * 5;
    m_buttonBack_game = new Button(m_sceneGame, "返回主页");
    m_buttonBack_game->setPos(tempX, tempY + 240);
    connect(m_buttonBack_game, &Button::clicked, this, &GameWin::switchTOwelcome);

    Button* button_online_demonic = new Button(m_sceneGame, "联机魔改");
    button_online_demonic->setPos(tempX + 155, tempY + 60);
    connect(button_online_demonic, &Button::clicked, this, &GameWin::online_demonic);

    Button* button_online_normal = new Button(m_sceneGame, "联机普通");
    button_online_normal->setPos(tempX - 155, tempY + 60);
    connect(button_online_normal, &Button::clicked, this, &GameWin::online_normal);

    Button* button_offline_demonic = new Button(m_sceneGame, "单人魔改");
    button_offline_demonic->setPos(tempX + 155, tempY - 120);
    connect(button_offline_demonic, &Button::clicked, this, &GameWin::offline_demonic);

    Button* button_offline_normal = new Button(m_sceneGame, "单人普通");
    button_offline_normal->setPos(tempX - 155, tempY - 120);
    connect(button_offline_normal, &Button::clicked, this, &GameWin::offline_normal);

    // 绘制标题
    QString strTitle("选择模式");
    QString htmlText = QString("<span style=\"font-family:'方正舒体';font-size:155px;font-weight:734;color:#5D5B5A;\">%1</span>")
            .arg(strTitle);
    QString htmlText_ready = QString("<span style=\"font-family:'方正舒体';font-size:155px;font-weight:734;color:#9729B0;\">%1</span>")
            .arg("!!!开战!!!");
    QGraphicsTextItem* title = new QGraphicsTextItem();
    title->setHtml(htmlText);
    title->setPos(tempX / 2 - 50 , tempY - 377);
    m_sceneGame->addItem(title);

    // 消失动画制作
    Game_Start = new QParallelAnimationGroup(this);
    Online_Start = new QParallelAnimationGroup(this);

    connect(Online_Start, &QParallelAnimationGroup::finished,
            this, &GameWin::switchToHall_ol);
    connect(Game_Start, &QParallelAnimationGroup::finished,[this, title](){
        // 移除文本图形项(没有重写碰撞)
        m_sceneGame->removeItem(title);

        // 重绘背景
        QPixmap tempPixmap(":/Monster_Kill/Res/Img/Back6.jpeg");
        QBrush tempBrush(tempPixmap);
        m_sceneGame->setBackgroundBrush(tempBrush);

        // 绘制棋盘
        m_board = new Board(m_sceneGame);
        m_board->setZValue(-1);
        m_board->setPos(WIN_WIDTH / 2, WIN_HEIGHT / 2);

        // 初始化卡牌
        initCard();
    });


    QPropertyAnimation* animation_back =
            new QPropertyAnimation(m_buttonBack_game, "opacity");
    animation_back->setDuration(788);
    animation_back->setEndValue(0);
    animation_back->setEasingCurve(QEasingCurve::Linear);
    Game_Start->addAnimation(animation_back);

    QPropertyAnimation* animation_online_demonic =
            new QPropertyAnimation(button_online_demonic, "opacity");
    animation_online_demonic->setDuration(788);
    animation_online_demonic->setEndValue(0);
    animation_online_demonic->setEasingCurve(QEasingCurve::Linear);
    Game_Start->addAnimation(animation_online_demonic);

    QPropertyAnimation* animaiotn_online_normal =
            new QPropertyAnimation(button_online_normal, "opacity");
    animaiotn_online_normal->setDuration(788);
    animaiotn_online_normal->setEndValue(0);
    animaiotn_online_normal->setEasingCurve(QEasingCurve::Linear);
    Game_Start->addAnimation(animaiotn_online_normal);

    QPropertyAnimation* animation_offline_demonic =
            new QPropertyAnimation(button_offline_demonic, "opacity");
    animation_offline_demonic->setDuration(788);
    animation_offline_demonic->setEndValue(0);
    animation_offline_demonic->setEasingCurve(QEasingCurve::Linear);
    Game_Start->addAnimation(animation_offline_demonic);

    QPropertyAnimation* animation_offline_normal =
            new QPropertyAnimation(button_offline_normal, "opacity");
    animation_offline_normal->setDuration(788);
    animation_offline_normal->setEndValue(0);
    animation_offline_normal->setEasingCurve(QEasingCurve::Linear);
    Game_Start->addAnimation(animation_offline_normal);

    QPropertyAnimation* animation_title_fade =
            new QPropertyAnimation(title, "opacity");
    animation_title_fade->setDuration(788);
    animation_title_fade->setEndValue(0);
    animation_title_fade->setEasingCurve(QEasingCurve::Linear);
    Game_Start->addAnimation(animation_title_fade);

    // 搬砖
    QPropertyAnimation* animation_back2 =
            new QPropertyAnimation(m_buttonBack_game, "opacity");
    animation_back2->setDuration(788);
    animation_back2->setEndValue(0);
    animation_back2->setEasingCurve(QEasingCurve::Linear);
    Online_Start->addAnimation(animation_back2);

    QPropertyAnimation* animation_online_demonic2 =
            new QPropertyAnimation(button_online_demonic, "opacity");
    animation_online_demonic2->setDuration(788);
    animation_online_demonic2->setEndValue(0);
    animation_online_demonic2->setEasingCurve(QEasingCurve::Linear);
    Online_Start->addAnimation(animation_online_demonic2);

    QPropertyAnimation* animaiotn_online_normal2 =
            new QPropertyAnimation(button_online_normal, "opacity");
    animaiotn_online_normal2->setDuration(788);
    animaiotn_online_normal2->setEndValue(0);
    animaiotn_online_normal2->setEasingCurve(QEasingCurve::Linear);
    Online_Start->addAnimation(animaiotn_online_normal2);

    QPropertyAnimation* animation_offline_demonic2 =
            new QPropertyAnimation(button_offline_demonic, "opacity");
    animation_offline_demonic2->setDuration(788);
    animation_offline_demonic2->setEndValue(0);
    animation_offline_demonic2->setEasingCurve(QEasingCurve::Linear);
    Online_Start->addAnimation(animation_offline_demonic2);

    QPropertyAnimation* animation_offline_normal2 =
            new QPropertyAnimation(button_offline_normal, "opacity");
    animation_offline_normal2->setDuration(788);
    animation_offline_normal2->setEndValue(0);
    animation_offline_normal2->setEasingCurve(QEasingCurve::Linear);
    Online_Start->addAnimation(animation_offline_normal2);

    QPropertyAnimation* animation_title_fade2 =
            new QPropertyAnimation(title, "opacity");
    animation_title_fade2->setDuration(788);
    animation_title_fade2->setEndValue(0);
    animation_title_fade2->setEasingCurve(QEasingCurve::Linear);
    Online_Start->addAnimation(animation_title_fade2);

}

void GameWin::initCard()
{
    m_welcomeBgm->stop();
    m_gameBgm->play();
    // 清空卡牌链表
    m_cardList.clear();

    // 红队
    m_cardElephant_red = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/elephant.png",
                              Card::RED, Card::ELEPHANT);
    m_cardTiger_red = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/tiger.png",
                              Card::RED, Card::TIGER);
    m_cardLion_red = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/lion.png",
                              Card::RED, Card::LION);
    m_cardCheetah_red = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/cheetah.png",
                                 Card::RED, Card::CHEETAH);
    m_cardWolf_red = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/wolf.png",
                              Card::RED, Card::WOLF);
    m_cardDog_red = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/dog.png",
                              Card::RED, Card::DOG);
    m_cardCat_red = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/cat.png",
                              Card::RED, Card::CAT);
    m_cardRat_red = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/rat.png",
                                 Card::RED, Card::RAT);

    // 蓝队
    m_cardElephant_blue = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/elephant.png",
                              Card::BLUE, Card::ELEPHANT);
    m_cardTiger_blue = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/tiger.png",
                              Card::BLUE, Card::TIGER);
    m_cardLion_blue = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/lion.png",
                              Card::BLUE, Card::LION);
    m_cardCheetah_blue = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/cheetah.png",
                                 Card::BLUE, Card::CHEETAH);
    m_cardWolf_blue = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/wolf.png",
                              Card::BLUE, Card::WOLF);
    m_cardDog_blue = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/dog.png",
                              Card::BLUE, Card::DOG);
    m_cardCat_blue = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/cat.png",
                              Card::BLUE, Card::CAT);
    m_cardRat_blue = new Card(m_sceneGame, ":/Monster_Kill/Res/Img/Animal/rat.png",
                                 Card::BLUE, Card::RAT);

    // 将卡牌装入链表
    m_cardList << m_cardElephant_red << m_cardTiger_red << m_cardLion_red << m_cardCheetah_red
               << m_cardWolf_red << m_cardDog_red << m_cardCat_red << m_cardRat_red;
    m_cardList << m_cardElephant_blue << m_cardTiger_blue << m_cardLion_blue << m_cardCheetah_blue
               << m_cardWolf_blue << m_cardDog_blue << m_cardCat_blue << m_cardRat_blue;

    m_faceList_red << m_cardRat_red->m_face << m_cardCat_red->m_face
                   << m_cardDog_red->m_face << m_cardWolf_red->m_face
                   << m_cardCheetah_red->m_face << m_cardLion_red->m_face
                   << m_cardTiger_red->m_face << m_cardElephant_red->m_face;

    m_faceList_blue << m_cardRat_blue->m_face << m_cardCat_blue->m_face
                    << m_cardDog_blue->m_face << m_cardWolf_blue->m_face
                    << m_cardCheetah_blue->m_face << m_cardLion_blue->m_face
                    << m_cardTiger_blue->m_face << m_cardElephant_blue->m_face;

    // 打乱卡牌顺序
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); // 生成种子
    std::default_random_engine generator(seed); // 创建随机数引擎;
    std::shuffle(m_cardList.begin(), m_cardList.end(), generator);

    // 设置状态机，用于摆放卡牌
    QState* orgState = new QState();
    QState* endState = new QState();
    int org_x = m_board->firstPoint().x();
    int org_y = m_board->firstPoint().y();

    for (int i = 0; i < m_cardList.count(); ++i) {
        m_cardList[i]->setZValue(5 + i);
        int row = i / 4;
        int col = i % 4;

        // 开始状态
        orgState->assignProperty(m_cardList[i], "pos", QPointF(WIN_WIDTH / 2, WIN_HEIGHT / 2));

        // 最终状态
        endState->assignProperty(m_cardList[i], "pos",
                                 QPoint(col * (CELL_WIDTH + CELL_MARGIN) + org_x,
                                 row * (CELL_HEIGHT + CELL_MARGIN) + org_y));
    }

    QStateMachine* states = new QStateMachine();
    states->addState(orgState);
    states->addState(endState);
    states->setInitialState(orgState);

    QParallelAnimationGroup* tempGroup = new QParallelAnimationGroup(this);
    for(int i = 0; i < m_cardList.count(); i++){
        QPropertyAnimation* tempAnimation =
                new QPropertyAnimation(m_cardList[i], "pos", tempGroup);
        tempAnimation->setDuration(897 + i * 50);
        tempAnimation->setEasingCurve(QEasingCurve::InOutBack);
    }

    m_startTimer = new QTimer();
    m_startTimer->setSingleShot(true);
    QSignalTransition* trans = orgState->addTransition(m_startTimer, SIGNAL(timeout()), endState);
    trans->addAnimation(tempGroup);

    m_startTimer->start(356);
    states->start();

    // 加载游戏管理器
    if(!m_isOnline){
        m_manager = new GameManager(m_sceneGame, &m_cardList, this);
        connect(m_manager, &GameManager::signal_humanOver, playerInfo, &PlayerInfo::setAiLabel);
        connect(m_manager, &GameManager::signal_aiOver, playerInfo, &PlayerInfo::setHumanLabel);
        emit cardReady();
    }

}

void GameWin::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    // 自定义paint事件
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);

    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void GameWin::switchTOhelp()
{
    m_View->setScene(m_sceneHelp);
}

void GameWin::switchTOgame()
{
    initGame();
    m_View->setScene(m_sceneGame);
}

void GameWin::switchTOwelcome()
{
    m_gameBgm->stop();
    m_welcomeBgm->play();
    m_View->setScene(m_scene);
}

void GameWin::switchToHall_ol()
{
    m_tcpSocket = new QTcpSocket(this);

    dialogOnline* hall = new dialogOnline(this, m_tcpSocket);
    connect(hall, &dialogOnline::signal_exit, [this, hall](){
        hall->close();
        switchTOgame();
    });
    connect(hall, &dialogOnline::signal_succ, [this, hall](){
        hall->close();
        switchTOgame_ol();
    });
    hall->exec();
}

void GameWin::tcpDown()
{
    qDebug() << "窗口接收到信息了";
    while(m_tcpSocket->bytesAvailable() >= sizeof(quint32)){
        QByteArray bt;
        QDataStream in(m_tcpSocket);
        in.setVersion(QDataStream::Qt_5_0);

        // 读取数据大小
        quint32 btSize;
        in >> btSize;
        if(m_tcpSocket->bytesAvailable() < btSize - sizeof(quint32)){
            break;
        }

        bt.resize(btSize - sizeof(quint32));
        in.readRawData(bt.data(), bt.size());

        QString tempStr = QString::fromUtf8(bt);
        tcpUse(tempStr);
        //qDebug() << tempStr;
    }
}

void GameWin::tcpUse(QString tempStr)
{
    if(tempStr[0] == "9"){ // 表示该信息是初始化
        tempStr.remove(0, 1);

        while(tempStr.length() > 0){
            int row = tempStr.mid(0, 1).toInt();
            int col = tempStr.mid(1, 1).toInt();
            int para1 = tempStr.mid(2, 1).toInt();
            Card::Group group = para1 == 1 ? Card::RED : Card::BLUE;
            int para2 = tempStr.mid(3, 1).toInt();
            Card::Monster_Type type =
                    static_cast<Card::Monster_Type>(para2);

            int tempIndex = row * 4 + col;
            m_cardList[tempIndex]->m_group = group;
            m_cardList[tempIndex]->m_type = type;
            if(group == Card::RED){
                m_cardList[tempIndex]->m_face = m_faceList_red[para2 - 1];
            }else{
                m_cardList[tempIndex]->m_face = m_faceList_blue[para2 - 1];
            }

            tempStr.remove(0, 4);
            //qDebug() << row <<" " << col << " " << group << " " << type;
        }
    }else if(tempStr[0] == "7"){ // 表示该信息是操作
        m_manager_ol->tcpUse(tempStr);
    }
}

void GameWin::switchTOgame_ol()
{
    m_isOnline = true;

    // 重绘背景
    QPixmap tempPixmap(":/Monster_Kill/Res/Img/Back6.jpeg");
    QBrush tempBrush(tempPixmap);
    m_sceneGame->setBackgroundBrush(tempBrush);

    // 绘制棋盘
    m_board = new Board(m_sceneGame);
    m_board->setZValue(-1);
    m_board->setPos(WIN_WIDTH / 2, WIN_HEIGHT / 2);

    // 初始化卡牌
    initCard();
    connect(m_tcpSocket, &QTcpSocket::readyRead, this, &GameWin::tcpDown);

    // 向服务器发送卡牌信息
    // 初始化标识符(9) + 行数 + 列数 + 阵营(1为红色，2为蓝色) + 类型
    // 比如923113022表示第二行第三列有一只红色的老鼠、第三行第一列有一直蓝色的猫
    QString tempStr = "9";
    for(int i = 0; i < m_cardList.count(); i++){
        QString row = QString::number(i / 4);
        QString col = QString::number(i % 4);
        int para = m_cardList.at(i)->m_group == Card::RED ? 1 : 2;
        QString tempGroup = QString::number(para);
        QString tempType = QString::number(m_cardList.at(i)->m_type);
        tempStr = tempStr + row + col + tempGroup + tempType;
    }
    tcpUp(tempStr.toUtf8());

    //disconnect(m_tcpSocket, &QTcpSocket::readyRead, this, &GameWin::tcpDown);
    m_manager_ol = new GameManagerOnline(m_tcpSocket, m_sceneGame, &m_cardList, this);
    Q_UNUSED(m_manager_ol);


}

void GameWin::tcpUp(QByteArray bt)
{
    QByteArray btPack;
    QDataStream out(&btPack, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_0); // 设置版本，保证跨平台兼容性
    out << quint32(0);

    quint32 btSize = bt.size() + sizeof(quint32);

    out << bt;
    btPack.remove(0, sizeof(quint32));
    out.device()->seek(0);
    out << btSize;

    m_tcpSocket->write(btPack);
}

void GameWin::offline_normal()
{

    Game_Start->start(QAbstractAnimation::DeleteWhenStopped);

    playerInfo = new PlayerInfo(this); // 信息部件
    playerInfo->move(WIN_WIDTH - 185, WIN_HEIGHT - 185);
    playerInfo->showLater();

    // 构造对话框
    DialogAsk* dialog_exit = new DialogAsk("确定要退出到主页?", this); // 退出对话框
    connect(dialog_exit, &DialogAsk::OkBtn, [this](){
        // 清空场景中的残余卡牌
        for(int i = 0; i < m_cardList.count(); i++){
            m_sceneGame->removeItem(m_cardList[i]);
        }
        delete playerInfo;
        this->switchTOwelcome();
    });

    DialogAsk* dialog_help = new DialogAsk("翻开/选中: 鼠标左键,\n移动:WASD->上下左右,\n克制关系: 象->虎->狮->豹->狼->犬->猫->鼠->象, 可越级击杀",
                                           this); // 帮助对话框

    DialogAsk* dialog_remake = new DialogAsk("确定要重新开始游戏么?", this); // 重开对话框
    connect(dialog_remake, &DialogAsk::OkBtn, [=](){
        // 清空场景中的残余卡牌
        for(int i = 0; i < m_cardList.count(); i++){
            m_sceneGame->removeItem(m_cardList[i]);
        }
        this->initCard();
        playerInfo->initControl();
    });

    // 构造圆形金属按钮
    RoundButton* roundBtn_exit = new RoundButton("退出");
    m_sceneGame->addItem(roundBtn_exit);
    roundBtn_exit->setPos(85, 85);
    connect(roundBtn_exit, &RoundButton::pressed, dialog_exit, &DialogAsk::showLater);

    RoundButton* roundBtn_help = new RoundButton("帮助");
    m_sceneGame->addItem(roundBtn_help);
    roundBtn_help->setPos(WIN_WIDTH - 85, 85);
    connect(roundBtn_help, &RoundButton::pressed, dialog_help, &DialogAsk::showLater);

    RoundButton* roundBtn_remake = new RoundButton("重开");
    m_sceneGame->addItem(roundBtn_remake);
    roundBtn_remake->setPos(85, WIN_HEIGHT - 85);
    connect(roundBtn_remake, &RoundButton::pressed, dialog_remake, &DialogAsk::showLater);

    // 令圆形金属按钮显出来
    connect(this, &GameWin::cardReady, [=](){
       roundBtn_exit->setVisible(true);
       roundBtn_help->setVisible(true);
       roundBtn_remake->setVisible(true);
    });

}

void GameWin::offline_demonic()
{

}

void GameWin::online_normal()
{
    Online_Start->start(QAbstractAnimation::DeleteWhenStopped);
}

void GameWin::online_demonic()
{

}

